# -*- coding:utf8 -*-
from django.db import models
from django.contrib.auth.admin import User
from datetime import datetime
from django.db.models import permalink
from django.contrib.sitemaps import ping_google

from ChineKingBlog.blog.fields import ThumbnailImageField
from ChineKingBlog.mptt.models import MPTTModel
from weibo import article_send2_weibo, comment_2_article, message_2_weibo

class Category(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField()
    order = models.IntegerField(blank=True, null=True)
    
    class Meta:
        verbose_name = "分类"
        verbose_name_plural = "分类"
        ordering = ['order',]
        
    def __unicode__(self):
        return self.name
    
    @ permalink
    def get_absolute_url(self):
        return ('program-category', None, {'slug': self.slug})
    
    def save(self):
        if self.order is None:
            cates = Category.objects.all()
            if cates:
                max_order = cates.order_by('-order')[0]
                self.order = max_order.order + 1
            else:
                self.order = 1
            
        super(Category, self).save()
        
        
class Tag(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField()
    
    articles = models.ManyToManyField("Article", through="Article_Tag")
    
    class Meta:
        verbose_name = "TAG"
        verbose_name_plural = "TAG"
        ordering = ['?']
        
    def __unicode__(self):
        return self.name
    
    @ permalink
    def get_absolute_url(self):
        return ('program-tag', None, {'slug': self.slug})
        
        
class Article(models.Model):
    STATUS_CHOICE = (
        (1, '编辑'),
        (2, '完成'),
        (3, '失效'),
    )
    
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)
    content = models.TextField()
    status = models.IntegerField(choices=STATUS_CHOICE,default=1)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(default=datetime.now)
    is_always_above = models.BooleanField(default=False)
    send_weibo = models.BooleanField(default=True)
    weibo_id = models.BigIntegerField(blank=True, null=True, editable=False)
    
    clicks = models.IntegerField(default=0, editable=False)
    
    category = models.ForeignKey(Category)
    author = models.ForeignKey(User)
    
    tags = models.ManyToManyField(Tag, through="Article_Tag")
    
    class Meta:
        verbose_name = "文章"
        verbose_name_plural = "文章"
        ordering = ['-is_always_above', '-created']
        
    def save(self):
        self.modified = datetime.now()
        super(Article, self).save()
        
        try:
            ping_google()
        except Exception:
            pass
        
        if self.send_weibo and self.weibo_id is None:
            send_weibo = article_send2_weibo(self)
            self.weibo_id = send_weibo()
            super(Article, self).save()
        
    def click_once(self):
        self.clicks += 1
        super(Article, self).save()
        
    def __unicode__(self):
        return self.title
    
    @ permalink
    def get_absolute_url(self):
        return ('program-article', None, {'slug': self.slug})
    
class basic_message(models.Model):
    username = models.CharField(max_length=50)
    email_address = models.EmailField()
    site = models.URLField(verify_exists=False, blank=True)
    avatar = models.URLField(blank=True, null=True)
    content = models.TextField()
    post_date = models.DateTimeField(editable=False, default=datetime.now)
    visible = models.BooleanField(default=True)
    
    class Meta:
        abstract = True
    
class Message(basic_message): 
    weibo_id = models.BigIntegerField(blank=True, null=True, editable=False)
    class Meta:
        ordering = ['-post_date']
        verbose_name = "留言"
        verbose_name_plural = "留言"
        
    def __unicode__(self):
        return self.content
    
    def message_to_weibo(self, token, tokenSecret):
        if self.weibo_id is None:
            m2weibo = message_2_weibo(self.content)
            self.weibo_id = m2weibo(token, tokenSecret)
            self.save()
                
    
class Comment(MPTTModel, basic_message):
    weibo_comment_id = models.BigIntegerField(blank=True, null=True, editable=False)
    
    article = models.ForeignKey(Article)
    reply_to_comment = models.ForeignKey("self", blank=True, null=True, related_name="children")
    
    class Meta:
        ordering = ['-post_date']
        verbose_name = u"\u8bc4\u8bba"
        verbose_name_plural = u"\u8bc4\u8bba"
        
    class MPTTMeta:
        parent_attr = 'reply_to_comment'
            
    def comment_to_weibo(self, token, tokenSecret):
        if self.reply_to_comment is None and self.weibo_comment_id is None \
        and self.article.weibo_id is not None:
            c2article = comment_2_article(self)
            self.weibo_comment_id = c2article(token, tokenSecret)
            self.save()       
            
    def __unicode__(self):
        return self.content
        
class Article_Tag(models.Model):
    article = models.ForeignKey(Article)
    tag = models.ForeignKey(Tag)
    
    class Meta:
        verbose_name = "文章Tags"
        verbose_name_plural = "文章Tags"
        
    def __unicode__(self):
        return unicode(self.tag)
        
        
class User_Info(models.Model):
    user = models.OneToOneField(User)
    
    info = models.TextField()
    avatar = ThumbnailImageField(upload_to="photos/avatar/", thumb_width=40, thumb_height=40)
    
    class Meta:
        verbose_name = "用户信息"
        verbose_name_plural = "用户信息"
        
    def __unicode__(self):
        return self.info